from time import sleep

import requests
import hashlib
import time



cookies = {
    'mtop_partitioned_detect': '1',
    '_m_h5_tk': '1f180f9cf6595421d8e64c167cc037955_1734088464136',
    '_m_h5_tk_enc': '91fcef393c937a3a56acc142985a50d2',
    'cna': 'gODiH1aq9QkCAWpTNjpF+ZZj',
    'cookie2': '154770c28e943677c6872a570345db4f',
    'xlly_s': '1',
    'tfstk': 'gznKIXAb4CAnUMZDxHTgZjNIeYviv0HE-Xkfq7VhPfhthx53PDqnwahnUb4WTkm-6YGvL8AEq9uZixsnxerl2krzVIADmnXELur5a3KTf6r_n82BqysQYl_jtvKvmnDEd92BnAtmxCVByWP7VyaSCNNaeg_SNyw_f5yzF6w5AdH__5w7dgNIC1wbhgsINu9tC5yPRuaIBcA819Nl24XurXiGmrI5VceL5FDQ1q0XEJzpEvVNVIGgpsPjd5I5VWclTIDtKBIqIkomM-cHfMhxFxu7W0C6M7otCDgSQ6d7Q4G3fWqXROEnYvgbPmOPPjEKwriQWTsLflF7XRiXEZPiXWcSvP9cDzqsmrZISFR3rkexNDldegGjIxmU70dA17u33lw-4K_8wzsPdmmxJF10M8bBBdQPzywZ8JqxwdrvCQeTipKRzazwQRFDBdQPzywaBSvpea7z7d5..',
}

headers = {
    'accept': 'application/json',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'cache-control': 'no-cache',
    'content-type': 'application/x-www-form-urlencoded',
    # 'cookie': 'mtop_partitioned_detect=1; _m_h5_tk=f180f9cf6595421d8e64c167cc037955_1734088464136; _m_h5_tk_enc=91fcef393c937a3a56acc142985a50d2; cna=gODiH1aq9QkCAWpTNjpF+ZZj; cookie2=154770c28e943677c6872a570345db4f; xlly_s=1; tfstk=gznKIXAb4CAnUMZDxHTgZjNIeYviv0HE-Xkfq7VhPfhthx53PDqnwahnUb4WTkm-6YGvL8AEq9uZixsnxerl2krzVIADmnXELur5a3KTf6r_n82BqysQYl_jtvKvmnDEd92BnAtmxCVByWP7VyaSCNNaeg_SNyw_f5yzF6w5AdH__5w7dgNIC1wbhgsINu9tC5yPRuaIBcA819Nl24XurXiGmrI5VceL5FDQ1q0XEJzpEvVNVIGgpsPjd5I5VWclTIDtKBIqIkomM-cHfMhxFxu7W0C6M7otCDgSQ6d7Q4G3fWqXROEnYvgbPmOPPjEKwriQWTsLflF7XRiXEZPiXWcSvP9cDzqsmrZISFR3rkexNDldegGjIxmU70dA17u33lw-4K_8wzsPdmmxJF10M8bBBdQPzywZ8JqxwdrvCQeTipKRzazwQRFDBdQPzywaBSvpea7z7d5..',
    'origin': 'https://www.goofish.com',
    'pragma': 'no-cache',
    'priority': 'u=1, i',
    'referer': 'https://www.goofish.com/',
    'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
}

while True:

    appKey = '34839810'
    time1 = int(time.time()*1000)
    params = {
        'jsv': '2.7.2',
        'appKey': '34839810',
        # 't': '1734079122852',
        # 'sign': '5694432b59ffe1444d6596a23e0e2ae3',
        'v': '1.0',
        'type': 'originaljson',
        'accountSite': 'xianyu',
        'dataType': 'json',
        'timeout': '20000',
        'api': 'mtop.taobao.idlemtopsearch.pc.search',
        'sessionOption': 'AutoLoginOnly',
        'spm_cnt': 'a21ybx.search.0.0',
        'spm_pre': 'a21ybx.home.searchInput.0',
    }



    data = {
        'data': '{"pageNumber":1,"keyword":"iphone16","fromFilter":false,"rowsPerPage":30,"sortValue":"","sortField":"","customDistance":"","gps":"","propValueStr":{},"customGps":"","searchReqFromPage":"pcSearch"}',
    }


    p = cookies['_m_h5_tk'].split('_')[0] + "&" + str(time1) + "&" + appKey + "&" + data['data']

    print(cookies['_m_h5_tk'].split('_')[0])
    sign = hashlib.md5(p.encode()).hexdigest()
    params['sign'] = sign
    params['t'] = str(time1)

    response = requests.post(
        'https://h5api.m.goofish.com/h5/mtop.taobao.idlemtopsearch.pc.search/1.0/',
        params=params,
        cookies=cookies,
        headers=headers,
        data=data,
    )


    print(response.json()['ret'][0]!='SUCCESS::调用成功')
    if(response.json()['ret'][0]!='SUCCESS::调用成功'):
        # 令牌有问题 更新令牌
        response2 = requests.post(
            'https://h5api.m.goofish.com/h5/mtop.taobao.idlemtopsearch.pc.search/1.0/',
            params=params,
            cookies=cookies,
            headers=headers,
            data=data,
        )
        print(response2.headers)
        # 在response.headers 中的 Set-Cookie 字符串中 拿到   _m_h5_tk
        # 解析 Set-Cookie 字段获取 _m_h5_tk 的值
        set_cookie = response2.headers.get('Set-Cookie', '')
        cookies1 = set_cookie.split(',')
        cookie_dict = {}
        for cookie in cookies1:
            parts = cookie.split(';')[0].strip()  # 获取每个cookie的第一部分并去除首尾空格
            if '=' in parts:
                key, value = parts.split('=', 1)
                cookie_dict[key] = value

        _m_h5_tk_value = cookie_dict.get('_m_h5_tk')
        _m_h5_tk_enc_value = cookie_dict.get('_m_h5_tk_enc')

        cookies['_m_h5_tk'] = _m_h5_tk_value
        cookies['_m_h5_tk_enc'] = _m_h5_tk_enc_value
    # for i in response.json()['data']['resultList']:
    #     try:
    #         print(i['data']['item']['main']['exContent']['detailParams']['title'])
    #     except:
    #         pass
    print(response.json()['ret'])
    sleep(5)
